import React, { useState } from 'react';
import { Modal, Form, Input, Switch, Row, Col, Typography, App } from 'antd';
import { UserOutlined, MailOutlined, LockOutlined, IdcardOutlined, CheckCircleOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Title } = Typography;

interface UserCreateModalProps {
    visible: boolean;
    onCancel: () => void;
    onSuccess: () => void;
}

const UserCreateModal: React.FC<UserCreateModalProps> = ({
    visible,
    onCancel,
    onSuccess,
}) => {
    const { message, notification } = App.useApp();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (values: any) => {
        setLoading(true);
        const token = localStorage.getItem('adminAuthToken');

        try {
            await axios.post('/api/admin/users/create/', values, {
                headers: { 'Authorization': `Token ${token}` }
            });

            // 显示成功通知
            notification.success({
                message: '用户创建成功',
                description: `用户 "${values.username}" 已成功创建，可以开始使用系统了`,
                placement: 'topRight',
                duration: 5,
                icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
            });

            form.resetFields();
            onSuccess();
        } catch (error: any) {
            console.error('Failed to create user:', error);

            // 处理验证错误
            if (error.response?.data) {
                const errorData = error.response.data;

                // 如果是字段验证错误，显示具体错误信息
                if (typeof errorData === 'object' && !errorData.error) {
                    let hasFieldErrors = false;
                    Object.keys(errorData).forEach(field => {
                        const fieldErrors = errorData[field];
                        if (Array.isArray(fieldErrors)) {
                            form.setFields([{
                                name: field,
                                errors: fieldErrors
                            }]);
                            hasFieldErrors = true;
                        }
                    });

                    if (hasFieldErrors) {
                        message.error('请检查表单中的错误信息');
                    }
                } else {
                    // 显示错误通知
                    notification.error({
                        message: '创建用户失败',
                        description: errorData.error || '请检查输入信息是否正确',
                        placement: 'topRight',
                        duration: 6,
                    });
                }
            } else {
                notification.error({
                    message: '创建用户失败',
                    description: '网络错误或服务器异常，请稍后重试',
                    placement: 'topRight',
                    duration: 6,
                });
            }
        } finally {
            setLoading(false);
        }
    };

    const handleCancel = () => {
        form.resetFields();
        onCancel();
    };

    return (
        <Modal
            title={
                <div style={{ textAlign: 'center' }}>
                    <UserOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                    <Title level={4} style={{ margin: 0, display: 'inline' }}>
                        创建新用户
                    </Title>
                </div>
            }
            open={visible}
            onCancel={handleCancel}
            onOk={() => form.submit()}
            confirmLoading={loading}
            width={600}
            destroyOnHidden
        >
            <Form
                form={form}
                layout="vertical"
                onFinish={handleSubmit}
                initialValues={{
                    is_active: true,
                    is_staff: false,
                    is_superuser: false,
                }}
            >
                <Row gutter={16}>
                    <Col span={12}>
                        <Form.Item
                            name="username"
                            label="用户名"
                            rules={[
                                { required: true, message: '请输入用户名' },
                                { min: 3, message: '用户名至少3个字符' },
                                { max: 20, message: '用户名最多20个字符' },
                                { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
                            ]}
                        >
                            <Input 
                                prefix={<UserOutlined />} 
                                placeholder="输入用户名"
                                autoComplete="off"
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            name="email"
                            label="邮箱地址"
                            rules={[
                                { required: true, message: '请输入邮箱地址' },
                                { type: 'email', message: '请输入有效的邮箱地址' }
                            ]}
                        >
                            <Input 
                                prefix={<MailOutlined />} 
                                placeholder="输入邮箱地址"
                                autoComplete="off"
                            />
                        </Form.Item>
                    </Col>
                </Row>



                <Row gutter={16}>
                    <Col span={12}>
                        <Form.Item
                            name="password"
                            label="密码"
                            rules={[
                                { required: true, message: '请输入密码' },
                                { min: 6, message: '密码至少6个字符' }
                            ]}
                        >
                            <Input.Password 
                                prefix={<LockOutlined />} 
                                placeholder="输入密码"
                                autoComplete="new-password"
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            name="confirm_password"
                            label="确认密码"
                            dependencies={['password']}
                            rules={[
                                { required: true, message: '请确认密码' },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('两次输入的密码不一致'));
                                    },
                                }),
                            ]}
                        >
                            <Input.Password 
                                prefix={<LockOutlined />} 
                                placeholder="再次输入密码"
                                autoComplete="new-password"
                            />
                        </Form.Item>
                    </Col>
                </Row>

                <Form.Item
                    name="nfc_card_id"
                    label="NFC卡号"
                >
                    <Input 
                        prefix={<IdcardOutlined />} 
                        placeholder="输入NFC卡号（可选）"
                        autoComplete="off"
                    />
                </Form.Item>

                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item
                            name="is_active"
                            label="账户状态"
                            valuePropName="checked"
                        >
                            <Switch 
                                checkedChildren="激活" 
                                unCheckedChildren="停用" 
                            />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="is_staff"
                            label="管理员权限"
                            valuePropName="checked"
                        >
                            <Switch 
                                checkedChildren="是" 
                                unCheckedChildren="否" 
                            />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="is_superuser"
                            label="超级管理员"
                            valuePropName="checked"
                        >
                            <Switch 
                                checkedChildren="是" 
                                unCheckedChildren="否" 
                            />
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
        </Modal>
    );
};

export default UserCreateModal;
